// 用户模块
import { defineStore } from 'pinia'
import { getUserInfo, switchAccount } from '@/api/user'
import { storageDict } from '@/config/dict'
import { dispatchCustomEvent } from '@/utils'
import { useAccountStore } from '../account'
import { closeToast, showToast } from 'vant'
import { useMainStore } from '../index'
import { _t18 } from '@/utils/public' // ✅ 使用自定义多语言函数
import { ignoreTokenError } from '@/utils/request' // ✅ 新增：防止切换时误登出

export const useUserStore = defineStore('user', {
  state: () => {
    return {
      /**
       * token
       */
      token: '',
      /**
       * 是否登录
       */
      isSign: ref(false),
      /**
       * 用户信息
       */
      userInfo: reactive({}),
      /**
       * 资产列表
       */
      asset: reactive([]),
      /**
       * 模拟盘标记
       */
      isDemo: ref(false), // ✅ 是否模拟盘
      /**
       * 切换状态锁
       */
      _switching: false // ✅ 防止频繁切换触发登出
    }
  },
  actions: {
    /**
     * 设置 token
     * @param {*} token
     */
    setToken(token) {
      this.token = token || ''
      localStorage.setItem(storageDict.TOKEN, this.token)
    },

    /**
     * 设置 登录状态
     * @param {*} isSign
     */
    setIsSign(isSign) {
      this.isSign = isSign
    },

    /**
     * 退出登录
     */
    signOut() {
      try {
        let testPlatform = localStorage.getItem(storageDict.TEST_PLATFORM)

        localStorage.clear()
        sessionStorage.clear()
        if (testPlatform) {
          localStorage.setItem(storageDict.TEST_PLATFORM, testPlatform)
        }
        this.$reset()
        const accountStore = useAccountStore()
        accountStore && accountStore.$reset()

        this.userInfo = null
        this.isSign = false
      } catch (error) {}
    },

    /**
     * 获取用户信息
     */
    async getUserInfo() {
      const res = await getUserInfo()
      if (res.code == 200) {
        Object.assign(this.userInfo, res.data || {})
        Object.assign(this.asset, this.userInfo.asset || [])
        dispatchCustomEvent('event_userInfoChange', this.userInfo)
        localStorage.setItem(storageDict.USER_INFO, JSON.stringify(this.userInfo))
        closeToast()
        const mainStore = useMainStore()
        mainStore.getUserRechageNew()
        return this.userInfo
      } else {
        closeToast()
      }
    },

    /**
     * ✅ 切换账户（实盘/模拟盘） — 最终修正版
     * @param {*} type 1=模拟盘，0=真实盘
     */
    async switchAccount(type = 1) {
      if (this._switching) return // 防止多次点击
      this._switching = true

      try {
        showToast('Loading...')
        const res = await switchAccount(type)
        closeToast()

        if (res.code === 200 && res.data) {
          const newToken = res.data.satoken
          if (!newToken) throw new Error('No token returned')

          // ✅ 更新 token
          this.setToken(newToken)
          this.setIsSign(true)
          this.isDemo = type === 1
          localStorage.setItem('isDemo', this.isDemo ? '1' : '0')

          // ✅ 防止切换时 axios token 检查误触发登出（关键）
          ignoreTokenError(4000)

          // ✅ 动态更新 axios headers
          const { default: axios } = await import('axios')
          axios.defaults.headers['satoken'] = newToken
          axios.defaults.headers['authorization'] = newToken

          // ✅ 延迟更新用户信息
          setTimeout(async () => {
            try {
              await this.getUserInfo()
              dispatchCustomEvent('event_userInfoChange', this.userInfo)
              showToast(this.isDemo ? _t18('22_switch_to_demo') : _t18('22_switch_to_real'))
            } catch (err) {
              console.warn('getUserInfo after switch failed:', err)
            }
          }, 500)
        } else {
          showToast('Network error, switch failed')
        }
      } catch (e) {
        closeToast()
        console.error('switchAccount error:', e)
        showToast('Network error, switch failed')
      } finally {
        this._switching = false
      }
    }
  },
  // 开启数据持久化
  persist: true
})
